package com.qilu.controller;

import com.qilu.domain.R;
import com.qilu.domain.dto.LoginDTO;
import com.qilu.domain.entity.SysUserEntity;
import com.qilu.service.SysUserService;
import com.qilu.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
public class LoginController extends BaseController{

    @Autowired
    SysUserService sysUserService;



    @PostMapping("login")
    public R login(@RequestBody LoginDTO param){
        // 1. 从数据库查询这个username的用户

        SysUserEntity user = sysUserService.getSysUserByUsername(param.getUsername());
        if (Objects.isNull(user)){
            return R.error("");
        }

        // 2. 对比用户的password

        boolean matches = passwordEncoder.matches(param.getPassword(), user.getPassword());
        if(!matches){
            return R.error("");
        }


        // 3. 发放token
        String token = JwtUtils.createToken(user.getId(), user.getRole());

        return R.success("登录成功",token);
    }
}
